﻿using ChurchDiary.BLL;
using ChurchDiary.Common;
using ChurchDiary.TableEntity;
using ChurchWebsite.JobDatas;
using Quartz;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace ChurchWebsite.Job
{
    public class EmailJob : IJob
    {
        public void Execute(IJobExecutionContext context)
        {
            List<EntityEmail> Emails = EmailJobData.GetPendingEmail();
            foreach (EntityEmail Email in Emails)
            {
                try
                {
                    MailMessage MailMessage = new MailMessage();
                    MailMessage.To.Add(new MailAddress(Email.EmailToAddress));

                    if (!string.IsNullOrEmpty(Email.EmailBcc))
                    {
                        MailMessage.Bcc.Add(Email.EmailBcc);
                    }
                    if (!string.IsNullOrEmpty(Email.EmailCC))
                    {
                        MailMessage.Bcc.Add(Email.EmailCC);
                    }
                    MailMessage.From = new MailAddress("noreplay@fgpc.in");
                    MailMessage.Subject = Email.EmailSubject;
                    MailMessage.IsBodyHtml = true;

                    string Content = EmailJobData.GetEmailTemplate(Email);
                    MailMessage.Body = Content;

                    SmtpClient smtpClient = new SmtpClient();
                    smtpClient.Host = "mail.fgpc.in"; //-- Donot change.
                    smtpClient.Port = 25; //--- Donot change
                    smtpClient.EnableSsl = false;//--- Donot change
                    smtpClient.UseDefaultCredentials = true;
                    smtpClient.Credentials = new System.Net.NetworkCredential("noreplay@fgpc.in", "Ju$t!n$a@m123");
                    smtpClient.Send(MailMessage);

                    Email.EmaiStatus = 1;
                    EmailJobData.UpdateEmailStatus(Email);
                }
                catch (Exception ex)
                {
                    Email.EmailSendOn = DateTime.Now;
                    Email.EmaiStatus = 2;
                    EmailJobData.UpdateEmailStatus(Email);
                }
            }
        }
    }
}